package controller;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //处理登录逻辑
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        if (userName==null||password==null||userName==""||password==""){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码为空");
            return;
        }
        UserDao userDao=new UserDao();
        User user=userDao.queryInfoByUserName(userName);
        if (user==null){
            //用户名不存在
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        if(!user.getPassword().equals(password)){
            //密码不匹配
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        HttpSession session=req.getSession(true);
        System.out.println(user.getNickName());
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }
//判断当前登录状态，并且设置状态码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession(false);
        if (session==null){
            //未登录
            resp.setStatus(403);
            return;
        }
        User user=new User();
        user= (User) session.getAttribute("user");
        if (user==null){
            resp.setStatus(403);
            return;
        }
        //登录成功
        resp.setStatus(200);
    }
}
